import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Subscription, switchMap, timer } from 'rxjs';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'app-check-es',
  standalone: true,
  imports: [CommonModule, HttpClientModule],
  template: `
    <p>
      check-es works!
    </p>
  `,
  styles: ``,
})
export class CheckEsComponent {
  private readonly ES_URL = 'http://localhost:9200';
  private readonly TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes in milliseconds
  private subscription!: Subscription;

  constructor(private http: HttpClient) {
  }

  ngOnInit() {
    this.checkElasticsearchStatus();
  }

  checkElasticsearchStatus(): void {
    this.subscription = timer(0, 5000).pipe(
        switchMap(() => this.checkConnection()),
    ).subscribe(response => {
      if (response.status === 200) {
        console.log('Elasticsearch is running');
        this.subscription.unsubscribe();
      } else if (response.status === 401) {
        console.error('Elasticsearch authentication failed');
        this.subscription.unsubscribe();
      }
    });

    // Timeout handling
    setTimeout(() => {
      if (!this.subscription.closed) {
        console.error('Elasticsearch request timed out');
        this.subscription.unsubscribe();
      }
    }, this.TIMEOUT_MS);
  }

  private async checkConnection(): Promise<Response> {
    try {
      return await fetch(this.ES_URL, {method: 'HEAD'});
    } catch (error) {
      console.error('Failed to connect to Elasticsearch:', error);
      return new Response(null, {status: 503, statusText: 'Service Unavailable'});
    }
  }

}
